//
//  BangoAppDelegate.m
//  Bango
//

#import "BangoAppDelegate.h"
#import "BGOAnalyticsConstants.h"
#import "BGOAnalyticsManager.h"
#import "BangoConfigConstants.h"
#import "BGOTransmissionModeConstants.h"
#import "BGOSessionEventsConstants.h"

@implementation BangoAppDelegate

@synthesize window;
@synthesize tabcontroller;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	/*
     BGO_ANALYTICS_DID_FINISH_LAUNCHING_WITH_OPTIONS_START
	 */
	
    // Init BangoAnalytics - setting the managed object context
	analytics_ = [BGOAnalyticsManager sharedManager];
	
	// set the uncaught exception handler
	NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
	
	// config options here
	analytics_.findLocation = YES;
	analytics_.debugLog = YES;
    //  analytics.postChunkSize = 12;
	analytics_.applicationChannel = @"DirectToDevice";
	analytics_.applicationType = @"test-application for analytics";
	analytics_.continueSessionSeconds = 10;
	//analytics.postUrl = SETTING_POST_DEV;
	analytics_.postUrl = BGO_SETTING_POST_URL_DEBUG;
	//analytics.userId = @"TommySimulator";
	
	// enable / disable event logging
	analytics_.loggingEnabled = YES;
	
	// set transmission to automatic
	analytics_.automaticDataTransmission = YES;
    
	//set logging level
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_VIDEOSTART,EVENT_VIDEOSTOP, nil] forLogLevel:LEVEL_VIDEO];
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_AUDIOSTART,EVENT_AUDIOSTOP, nil] forLogLevel:LEVEL_AUDIO];
    [analytics_ setEvents:[NSArray arrayWithObjects:EVENT_PAGEVIEW,EVENT_SEARCH, nil]      forLogLevel:LEVEL_PAGEVIEW_AND_SEARCH];

    //<app id is set here>
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [[NSUserDefaults standardUserDefaults] setValue:BANGO_IPAD_APPLICATION_ID forKey:BANGO_APPLICATION_ID];
             
    } 
    else 
    {                
        [[NSUserDefaults standardUserDefaults] setValue:BANGO_IPHONE_APPLICATION_ID forKey:BANGO_APPLICATION_ID];
        // Running on iPhone or iPod touch
        
    }
   
	[analytics_ onStartSessionWithApplicationId:[[NSUserDefaults standardUserDefaults] objectForKey:BANGO_APPLICATION_ID]];
    NSLog(@"log %@",[[NSUserDefaults standardUserDefaults] objectForKey:BANGO_APPLICATION_ID]);

	// try and post any data which is not the current profile we have just created
	// no need to use this if automaticDataTransmission is enabled
	// [analytics commenceTransmissionWithMode:TRANSMIT_EXCLUDE_LATEST];
	
	/*
	 BGO_ANALYTICS_DID_FINISH_LAUNCHING_WITH_OPTIONS_END
	 */ 
	
	// Override point for customization after application launch.
	[window addSubview:tabcontroller.view];
    [window makeKeyAndVisible];
	
	return YES;
}

void uncaughtExceptionHandler(NSException *exception) {
	BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
	
	NSMutableString *exceptionString = [NSMutableString stringWithString:@"name: "];
	[exceptionString appendString:exception.name];
	[exceptionString appendString:@" reason: "];
	[exceptionString appendString:exception.reason];
	
	NSNumber * errorLevel = [NSNumber numberWithInt:BGO_ERROR_INTERNAL_CRITICAL];
    
	[analytics onErrorWithEventParameters:nil message:exception.name eventClass:@"Uncaught Exception"
                          eventErrorLevel:errorLevel eventErrorId:exceptionString];
}     


- (void)applicationWillResignActive:(UIApplication *)application {
	NSLog(@"> %s", __PRETTY_FUNCTION__);
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_RESIGN_ACTIVE_START
	 */
	
    // Log Idle Event
    UIDevice * device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
        backgroundSupported = device.multitaskingSupported;
    }

    if (backgroundSupported) {
        UIApplication * app = [UIApplication sharedApplication];
        
        backgroundTaskId_ = [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:backgroundTaskId_];
            backgroundTaskId_ = UIBackgroundTaskInvalid;
        }];
        
        // Start the long-running task and return immediately.
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            // Do the work associated with the task.
            // BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
			
			// If the user agent string is NIL then we've not initialised the user agent yet, which 
			// means it is unsafe to invoke the Analytics Singleton from the resign active state

			if ([analytics_ userAgent] != nil)
            	[analytics_ onIdleWithEventParameters:nil 
                                     	eventDetail:@"applicationWillResignActive"
                                      	eventValue:nil fromBackground:YES];
            
            [app endBackgroundTask:backgroundTaskId_];
            backgroundTaskId_ = UIBackgroundTaskInvalid;
        });
    } else {
		// No multitasking support so make a regular call to onIdle... 
		//BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
		
			// If the user agent string is NIL then we've not initialised the user agent yet, which 
			// means it is unsafe to invoke the Analytics Singleton from the resign active state

			if ([analytics_ userAgent] != nil)
				[analytics_ onIdleWithEventParameters:nil
				eventDetail:@"applicationWillResignActive" 
				eventValue:nil];
		
	}
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_RESIGN_ACTIVE_END
	 */ 
	
	
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
	NSLog(@"> %s", __PRETTY_FUNCTION__);
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_ENTER_FOREGROUND_START
	 */
	
    // Log Idle Event
	// BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
	[analytics_ onResumeWithEventParameters:nil eventDetail:@"applicationWillEnterForeground" eventValue:nil];
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_ENTER_FOREGROUND_END
	 */ 
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
	NSLog(@"> %s", __PRETTY_FUNCTION__);
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
	
	// This method is called when the app lanunches for the first time as well as when coming out of idle state - therefore we should not log
	// Bango Analytics onResume here. Should log in applicationWillEnterForeground as that seems to be only called
	// when coming out of idle state.
}


/**
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	NSLog(@"> %s", __PRETTY_FUNCTION__);
    
    //    NSError *error = nil;
    //    if (managedObjectContext_ != nil) {
    //        if ([managedObjectContext_ hasChanges] && ![managedObjectContext_ save:&error]) {
    //            /*
    //             Replace this implementation with code to handle the error appropriately.
    //             
    //             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
    //             */
    //            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    //			//abort();
    //        } 
    //    }
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_TERMINATE_START
	 */
	
    // Log Idle Event
	//BGOAnalyticsManager *analytics = [BGOAnalyticsManager sharedManager];
	[analytics_ onEndSessionWithEventParameters:nil eventDetail:@"applicationWillTerminate" eventValue:nil];
	
	/*
	 BGO_ANALYTICS_APPLICATION_WILL_TERMINATE_END
	 */ 
}


// Obtains reference to the app delegate
+ (BangoAppDelegate *)sharedAppDelegate
{
    return (BangoAppDelegate *)[UIApplication sharedApplication].delegate;
}

#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	[tabcontroller release];
	
    [window release];
    [super dealloc];
}


@end

